<template>
  <div class="travel-guide-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>旅游攻略管理</span>
          <el-button type="primary" @click="handleAdd">发布攻略</el-button>
        </div>
      </template>
      
      <!-- 搜索区域 -->
      <div class="search-area">
        <el-form :inline="true" :model="searchForm" class="demo-form-inline">
          <el-form-item label="目的地">
            <el-input v-model="searchForm.destination" placeholder="请输入目的地" />
          </el-form-item>
          <el-form-item label="作者">
            <el-input v-model="searchForm.author" placeholder="请输入作者" />
          </el-form-item>
          <el-form-item label="发布时间">
            <el-date-picker
              v-model="searchForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 表格区域 -->
      <el-table :data="paginatedData" style="width: 100%" v-loading="loading">
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="title" label="标题" min-width="180" show-overflow-tooltip />
        <el-table-column prop="destination" label="目的地" width="100" align="center" />
        <el-table-column prop="author" label="作者" width="100" align="center" />
        <el-table-column prop="createTime" label="发布时间" width="160" align="center" />
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="审核状态" width="180" align="center">
          <template #default="scope">
            <div class="audit-status">
              <el-tag v-if="scope.row.auditStatus === 'pending'" type="warning">待审核</el-tag>
              <el-tag v-else-if="scope.row.auditStatus === 'approved'" type="success">已通过</el-tag>
              <el-tag v-else-if="scope.row.auditStatus === 'rejected'" type="danger">已拒绝</el-tag>
              <div class="audit-actions">
                <el-button 
                  v-if="scope.row.auditStatus === 'pending'"
                  size="small" 
                  type="primary" 
                  @click="handleAudit(scope.row)"
                >
                  开始审核
                </el-button>
                <el-button
                  v-if="scope.row.auditStatus === 'rejected'"
                  size="small"
                  type="info"
                  class="audit-comment-btn"
                  @click="showAuditComment(scope.row)"
                >
                  查看审核意见
                </el-button>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="isPublished" label="是否下架" width="100" align="center">
          <template #default="scope">
            <el-switch
              v-model="scope.row.isPublished"
              :disabled="scope.row.auditStatus !== 'approved'"
              :active-text="scope.row.isPublished ? '已下架' : '未下架'"
              @change="handlePublishChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" align="center">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
            <el-button size="small" type="info" class="history-btn" @click="handleViewHistory(scope.row)">编辑历史</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '发布攻略' : '编辑攻略'"
      width="70%"
    >
      <el-form :model="form" label-width="120px" :rules="rules">
        <el-form-item label="标题">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="目的地">
          <el-input v-model="form.destination" placeholder="请输入目的地" />
        </el-form-item>
        <el-form-item label="景点介绍">
          <el-input
            v-model="form.attractions"
            type="textarea"
            :rows="4"
            placeholder="请输入景点介绍"
          />
        </el-form-item>
        <el-form-item label="行程安排">
          <el-input
            v-model="form.itinerary"
            type="textarea"
            :rows="4"
            placeholder="请输入行程安排"
          />
        </el-form-item>
        <el-form-item label="交通方式">
          <el-input
            v-model="form.transportation"
            type="textarea"
            :rows="3"
            placeholder="请输入交通方式"
          />
        </el-form-item>
        <el-form-item label="住宿推荐">
          <el-input
            v-model="form.accommodation"
            type="textarea"
            :rows="3"
            placeholder="请输入住宿推荐"
          />
        </el-form-item>
        <el-form-item label="美食推荐">
          <el-input
            v-model="form.food"
            type="textarea"
            :rows="3"
            placeholder="请输入美食推荐"
          />
        </el-form-item>
        <el-form-item label="上传图片">
          <el-upload
            action="/api/upload"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-success="handleUploadSuccess"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 审核对话框 -->
    <el-dialog
      v-model="auditDialogVisible"
      title="攻略审核"
      width="70%"
    >
      <el-form :model="auditForm" label-width="120px">
        <el-form-item label="标题">
          <span>{{ currentAuditGuide.title }}</span>
        </el-form-item>
        <el-form-item label="目的地">
          <span>{{ currentAuditGuide.destination }}</span>
        </el-form-item>
        <el-form-item label="作者">
          <span>{{ currentAuditGuide.author }}</span>
        </el-form-item>
        <el-form-item label="发布时间">
          <span>{{ currentAuditGuide.createTime }}</span>
        </el-form-item>
        <el-form-item label="景点介绍">
          <div class="content-box">{{ currentAuditGuide.attractions }}</div>
        </el-form-item>
        <el-form-item label="行程安排">
          <div class="content-box">{{ currentAuditGuide.itinerary }}</div>
        </el-form-item>
        <el-form-item label="交通方式">
          <div class="content-box">{{ currentAuditGuide.transportation }}</div>
        </el-form-item>
        <el-form-item label="住宿推荐">
          <div class="content-box">{{ currentAuditGuide.accommodation }}</div>
        </el-form-item>
        <el-form-item label="美食推荐">
          <div class="content-box">{{ currentAuditGuide.food }}</div>
        </el-form-item>
        <el-form-item label="上传图片" v-if="currentAuditGuide.images && currentAuditGuide.images.length > 0">
          <el-image
            v-for="(url, index) in currentAuditGuide.images"
            :key="index"
            :src="url"
            :preview-src-list="currentAuditGuide.images"
            fit="cover"
            class="preview-image"
          />
        </el-form-item>
        <el-divider />
        <el-form-item label="审核结果">
          <el-radio-group v-model="auditForm.result">
            <el-radio label="approved">通过</el-radio>
            <el-radio label="rejected">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核意见" v-if="auditForm.result === 'rejected'">
          <el-input
            v-model="auditForm.comment"
            type="textarea"
            :rows="4"
            placeholder="请输入拒绝原因"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="auditDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAudit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑历史对话框 -->
    <el-dialog
      v-model="historyDialogVisible"
      title="编辑历史"
      width="60%"
    >
      <el-timeline>
        <el-timeline-item
          v-for="(history, index) in editHistory"
          :key="index"
          :timestamp="history.time"
          :type="history.type"
        >
          {{ history.content }}
        </el-timeline-item>
      </el-timeline>
    </el-dialog>

    <!-- 审核意见对话框 -->
    <el-dialog
      v-model="commentDialogVisible"
      title="审核意见"
      width="30%"
    >
      <div class="audit-comment-content">
        {{ currentAuditComment }}
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="commentDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/stores/user'

const userStore = useUserStore()

// 日期工具函数
const dateUtils = {
  // 格式化日期为 YYYY-MM-DD HH:mm:ss
  formatDateTime: (date) => {
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  },
  
  // 设置日期为当天的开始时间 (00:00:00.000)
  setStartOfDay: (date) => {
    const newDate = new Date(date)
    newDate.setHours(0, 0, 0, 0)
    return newDate
  },
  
  // 设置日期为当天的结束时间 (23:59:59.999)
  setEndOfDay: (date) => {
    const newDate = new Date(date)
    newDate.setHours(23, 59, 59, 999)
    return newDate
  },
  
  // 检查日期是否在范围内
  isDateInRange: (date, startDate, endDate) => {
    const checkDate = new Date(date)
    const start = dateUtils.setStartOfDay(startDate)
    const end = dateUtils.setEndOfDay(endDate)
    return checkDate >= start && checkDate <= end
  }
}

const tableData = ref([
  {
    id: 1,
    title: '沙扒湾经典三日游攻略',
    destination: '沙扒湾',
    author: '张三',
    createTime: '2024-06-01 10:00:00',
    status: 'approved',
    auditStatus: 'approved',
    isPublished: false,
    originalIsPublished: false,
    attractions: '沙扒湾有美丽的海滩和清澈的海水，是广东省著名的海滨旅游胜地。这里有着绵延数公里的金色沙滩，海水清澈见底，是游泳、冲浪和日光浴的理想场所。',
    itinerary: '第一天：到达沙扒湾，入住酒店，休息；\n第二天：游览海滩，品尝海鲜；\n第三天：体验海上项目，参观渔村；\n第四天：购物，返程。',
    transportation: '可以乘坐高铁到附近城市，再转乘汽车到达沙扒湾。\n自驾路线：从广州出发，沿广湛高速行驶约3小时可到达。',
    accommodation: '推荐沙扒湾海景酒店，价格实惠，景色优美。\n其他选择：\n1. 沙扒湾度假村\n2. 海景公寓\n3. 渔村民宿',
    food: '沙扒湾的海鲜非常新鲜，推荐品尝：\n1. 清蒸螃蟹\n2. 白灼虾\n3. 蒜蓉蒸扇贝\n4. 海鲜粥',
    images: ['/images/shabawan1.jpg', '/images/shabawan2.jpg']
  },
  {
    id: 2,
    title: '沙扒湾亲子游攻略',
    destination: '沙扒湾',
    author: '李四',
    createTime: '2024-06-02 14:30:00',
    status: 'pending',
    auditStatus: 'pending',
    isPublished: false,
    originalIsPublished: false,
    attractions: '沙扒湾是亲子游的绝佳选择，这里有适合儿童的浅水区，沙滩细腻，海水清澈。周边还有儿童游乐设施和亲子活动项目，让全家人都能玩得开心。',
    itinerary: '第一天：到达沙扒湾，入住亲子主题酒店；\n第二天：沙滩亲子活动，体验儿童游乐设施；\n第三天：参观海洋馆，体验亲子互动项目；\n第四天：购物，返程。',
    transportation: '建议自驾前往，方便携带儿童用品。\n也可以选择包车服务，提供儿童安全座椅。',
    accommodation: '推荐亲子主题酒店：\n1. 沙扒湾亲子度假酒店\n2. 海景家庭套房\n3. 儿童主题民宿',
    food: '适合儿童的特色美食：\n1. 海鲜粥\n2. 清蒸鱼\n3. 水果拼盘\n4. 儿童营养餐',
    images: ['/images/shabawan3.jpg', '/images/shabawan4.jpg']
  },
  {
    id: 3,
    title: '沙扒湾美食攻略',
    destination: '沙扒湾',
    author: '赵六',
    createTime: '2024-06-04 16:45:00',
    status: 'approved',
    auditStatus: 'approved',
    isPublished: false,
    originalIsPublished: false,
    attractions: '沙扒湾不仅是旅游胜地，更是美食天堂。这里有最新鲜的海鲜，独特的渔村美食，以及各种特色小吃，让您品尝到最地道的海边美食。',
    itinerary: '第一天：品尝海鲜大餐；\n第二天：体验渔村美食；\n第三天：探索特色小吃；\n第四天：购买特产，返程。',
    transportation: '可以乘坐高铁到附近城市，再转乘汽车到达。\n也可以选择美食主题包车服务。',
    accommodation: '推荐美食主题住宿：\n1. 海鲜主题酒店\n2. 渔村特色民宿\n3. 美食街附近酒店',
    food: '必尝美食：\n1. 清蒸大闸蟹\n2. 白灼基围虾\n3. 蒜蓉蒸扇贝\n4. 海鲜粥\n5. 渔村特色菜',
    images: ['/images/shabawan7.jpg', '/images/shabawan8.jpg']
  },
  {
    id: 4,
    title: '沙扒湾深度游攻略',
    destination: '沙扒湾',
    author: '钱七',
    createTime: '2024-06-05 11:20:00',
    status: 'pending',
    auditStatus: 'pending',
    isPublished: false,
    originalIsPublished: false,
    attractions: '沙扒湾深度游带您探索这个海滨小镇的每一个角落，从历史古迹到自然风光，从渔村文化到现代设施，让您深入了解沙扒湾的魅力。',
    itinerary: '第一天：探索历史古迹，了解当地文化；\n第二天：体验渔村生活，参与渔民活动；\n第三天：探索自然风光，体验海上项目；\n第四天：购物，返程。',
    transportation: '建议自驾或包车，方便探索各个景点。\n也可以选择当地特色交通工具。',
    accommodation: '推荐特色住宿：\n1. 渔村特色民宿\n2. 海景度假酒店\n3. 文化主题客栈',
    food: '特色美食：\n1. 渔村特色菜\n2. 海鲜大餐\n3. 当地小吃\n4. 特色饮品',
    images: ['/images/shabawan9.jpg', '/images/shabawan10.jpg']
  }
])

const searchForm = ref({
  destination: '',
  author: '',
  dateRange: []
})

const dialogType = ref('')
const dialogVisible = ref(false)
const form = ref({
  title: '',
  destination: '',
  attractions: '',
  itinerary: '',
  transportation: '',
  accommodation: '',
  food: '',
  images: []
})

// 编辑历史相关
const historyDialogVisible = ref(false)
const editHistory = ref([])
const currentHistoryGuide = ref(null)

// 模拟持久化存储的历史记录
const guideHistoryMap = ref(new Map())

// 编辑历史类型
const historyTypes = {
  CREATE: {
    label: '创建',
    type: 'primary'
  },
  UPDATE: {
    label: '更新',
    type: 'success'
  },
  AUDIT_APPROVED: {
    label: '审核通过',
    type: 'success'
  },
  AUDIT_REJECTED: {
    label: '审核拒绝',
    type: 'danger'
  },
  PUBLISH: {
    label: '发布',
    type: 'success'
  },
  UNPUBLISH: {
    label: '下架',
    type: 'info'
  }
}

// 生成历史记录
const createHistoryRecord = (type, content, extraInfo = {}) => {
  return {
    id: Date.now() + Math.random().toString(36).substr(2, 9), // 生成唯一ID
    type: historyTypes[type].type,
    typeLabel: historyTypes[type].label,
    content,
    operator: userStore.nickname || '未知用户',
    time: dateUtils.formatDateTime(new Date()),
    ...extraInfo
  }
}

// 保存历史记录
const saveHistory = (guideId, record) => {
  if (!guideHistoryMap.value.has(guideId)) {
    guideHistoryMap.value.set(guideId, [])
  }
  const history = guideHistoryMap.value.get(guideId)
  history.unshift(record)
  guideHistoryMap.value.set(guideId, history)
  
  // 如果当前正在查看该攻略的历史，则更新显示
  if (currentHistoryGuide.value?.id === guideId) {
    editHistory.value = [...history]
  }
}

const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(tableData.value.length)
const loading = ref(false)

// 审核相关
const auditDialogVisible = ref(false)
const currentAuditGuide = ref({})
const auditForm = ref({
  result: 'approved',
  comment: ''
})

// 审核意见相关
const commentDialogVisible = ref(false)
const currentAuditComment = ref('')

// 保存原始数据
const originalTableData = ref([...tableData.value])

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' },
    { min: 2, max: 50, message: '标题长度应在2-50个字符之间', trigger: 'blur' }
  ],
  destination: [
    { required: true, message: '请输入目的地', trigger: 'blur' }
  ],
  attractions: [
    { required: true, message: '请输入景点介绍', trigger: 'blur' }
  ],
  itinerary: [
    { required: true, message: '请输入行程安排', trigger: 'blur' }
  ]
}

// 计算当前页显示的数据
const paginatedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return tableData.value.slice(start, end)
})

// 搜索
const handleSearch = () => {
  const { destination, author, dateRange } = searchForm.value
  
  // 重置分页
  currentPage.value = 1
  
  // 过滤数据
  const filteredData = tableData.value.filter(item => {
    // 目的地匹配（不区分大小写）
    const destinationMatch = !destination || 
      item.destination.toLowerCase().includes(destination.toLowerCase())
    
    // 作者匹配（不区分大小写）
    const authorMatch = !author || 
      item.author.toLowerCase().includes(author.toLowerCase())
    
    // 日期范围匹配
    let dateMatch = true
    if (dateRange && dateRange.length === 2 && dateRange[0] && dateRange[1]) {
      dateMatch = dateUtils.isDateInRange(
        item.createTime,
        dateRange[0],
        dateRange[1]
      )
    }
    
    return destinationMatch && authorMatch && dateMatch
  })
  
  // 更新总数
  total.value = filteredData.length
  
  // 更新表格数据
  tableData.value = filteredData

  // 显示搜索结果提示
  ElMessage({
    type: 'success',
    message: `查询到 ${filteredData.length} 条记录`
  })
}

// 重置搜索
const resetSearch = () => {
  searchForm.value.destination = ''
  searchForm.value.author = ''
  searchForm.value.dateRange = []
  
  // 重置分页
  currentPage.value = 1
  
  // 恢复原始数据
  tableData.value = [...originalTableData.value]
  
  // 更新总数
  total.value = tableData.value.length

  // 显示重置提示
  ElMessage({
    type: 'info',
    message: '已重置搜索条件'
  })
}

// 获取当前时间
const getCurrentTime = () => {
  return dateUtils.formatDateTime(new Date())
}

// 处理新增
const handleAdd = () => {
  dialogType.value = 'add'
  dialogVisible.value = true
  // 重置表单
  Object.keys(form.value).forEach(key => {
    form.value[key] = ''
  })
  form.value.images = []
  // 自动设置作者和发布时间
  form.value.author = userStore.nickname || '未知用户'
  form.value.createTime = getCurrentTime()
}

// 处理编辑
const handleEdit = (row) => {
  dialogType.value = 'edit'
  dialogVisible.value = true
  // 深拷贝数据，避免直接修改原数据
  form.value = {
    id: row.id,
    title: row.title,
    destination: row.destination,
    attractions: row.attractions,
    itinerary: row.itinerary,
    transportation: row.transportation,
    accommodation: row.accommodation,
    food: row.food,
    images: [...(row.images || [])],
    author: row.author,
    createTime: row.createTime,
    status: row.status,
    auditStatus: row.auditStatus,
    isPublished: row.isPublished,
    originalIsPublished: row.originalIsPublished,
    auditComment: row.auditComment
  }
}

// 处理删除
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确定要删除该攻略吗？删除后不可恢复！',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    const index = tableData.value.findIndex(item => item.id === row.id)
    if (index !== -1) {
      tableData.value.splice(index, 1)
      total.value = tableData.value.length
      ElMessage.success('删除成功')
    }
  })
}

// 处理审核
const handleAudit = (row) => {
  currentAuditGuide.value = { ...row }
  auditForm.value = {
    result: 'approved',
    comment: ''
  }
  auditDialogVisible.value = true
}

// 处理查看编辑历史
const handleViewHistory = (row) => {
  currentHistoryGuide.value = row
  historyDialogVisible.value = true
  loadEditHistory(row)
}

// 加载编辑历史
const loadEditHistory = (guide) => {
  // 如果没有历史记录，创建初始记录
  if (!guideHistoryMap.value.has(guide.id)) {
    const initialHistory = []
    
    // 创建记录
    initialHistory.push(createHistoryRecord(
      'CREATE',
      '创建了攻略',
      {
        time: guide.createTime
      }
    ))

    // 如果有审核记录
    if (guide.auditStatus === 'approved') {
      initialHistory.push(createHistoryRecord(
        'AUDIT_APPROVED',
        '审核通过了该攻略'
      ))
    } else if (guide.auditStatus === 'rejected') {
      initialHistory.push(createHistoryRecord(
        'AUDIT_REJECTED',
        `审核拒绝：${guide.auditComment || '无理由'}`
      ))
    }

    // 发布状态变更记录
    if (guide.isPublished) {
      initialHistory.push(createHistoryRecord(
        'PUBLISH',
        '发布了攻略'
      ))
    }

    guideHistoryMap.value.set(guide.id, initialHistory)
  }

  // 获取并显示历史记录
  editHistory.value = [...guideHistoryMap.value.get(guide.id)]
}

// 添加历史记录
const addEditHistory = (guide, type, content) => {
  const record = createHistoryRecord(type, content)
  saveHistory(guide.id, record)
}

// 处理发布状态变更
const handlePublishChange = (row) => {
  if (row.auditStatus !== 'approved') {
    ElMessage.warning('该攻略尚未通过审核，无法修改发布状态')
    row.isPublished = !row.isPublished // 恢复原状态
    return
  }

  ElMessageBox.confirm(
    `确定要${row.isPublished ? '下架' : '发布'}该攻略吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 添加发布/下架历史记录
    addEditHistory(
      row,
      row.isPublished ? 'UNPUBLISH' : 'PUBLISH',
      row.isPublished ? '下架了攻略' : '发布了攻略'
    )
    
    ElMessage.success(row.isPublished ? '已下架' : '已发布')
  }).catch(() => {
    row.isPublished = !row.isPublished // 取消操作，恢复状态
  })
}

// 处理图片上传成功
const handleUploadSuccess = (response, file) => {
  form.value.images.push(response.url)
}

// 处理图片预览
const handlePictureCardPreview = (file) => {
  // 这里可以实现图片预览逻辑
}

// 处理图片移除
const handleRemove = (file) => {
  const index = form.value.images.indexOf(file.url)
  if (index !== -1) {
    form.value.images.splice(index, 1)
  }
}

// 处理表单提交
const handleSubmit = async () => {
  if (!form.value.title?.trim() || !form.value.destination?.trim() || 
      !form.value.attractions?.trim() || !form.value.itinerary?.trim()) {
    ElMessage.warning('请填写必要的信息（标题、目的地、景点介绍、行程安排）')
    return
  }

  try {
    if (dialogType.value === 'add') {
      const newId = tableData.value.length > 0 ? Math.max(...tableData.value.map(item => item.id)) + 1 : 1
      const newGuide = {
        ...form.value,
        id: newId,
        status: 'pending',
        auditStatus: 'pending',
        isPublished: false,
        originalIsPublished: false,
        auditComment: '',
        author: userStore.nickname || '未知用户',
        createTime: getCurrentTime(),
        updateTime: getCurrentTime()
      }
      tableData.value.push(newGuide)
      total.value = tableData.value.length
      
      addEditHistory(newGuide, 'CREATE', '创建了攻略')
      ElMessage.success('发布成功，等待审核')
    } else {
      const index = tableData.value.findIndex(item => item.id === form.value.id)
      if (index !== -1) {
        const originalGuide = tableData.value[index]
        
        // 记录修改的字段
        const changedFields = []
        if (originalGuide.title !== form.value.title) changedFields.push('标题')
        if (originalGuide.destination !== form.value.destination) changedFields.push('目的地')
        if (originalGuide.attractions !== form.value.attractions) changedFields.push('景点介绍')
        if (originalGuide.itinerary !== form.value.itinerary) changedFields.push('行程安排')
        if (originalGuide.transportation !== form.value.transportation) changedFields.push('交通方式')
        if (originalGuide.accommodation !== form.value.accommodation) changedFields.push('住宿推荐')
        if (originalGuide.food !== form.value.food) changedFields.push('美食推荐')

        if (changedFields.length === 0) {
          ElMessage.warning('未检测到任何修改')
          return
        }

        const updatedGuide = {
          ...originalGuide,
          title: form.value.title,
          destination: form.value.destination,
          attractions: form.value.attractions,
          itinerary: form.value.itinerary,
          transportation: form.value.transportation,
          accommodation: form.value.accommodation,
          food: form.value.food,
          images: [...(form.value.images || [])],
          updateTime: getCurrentTime()
        }
        
        if (originalGuide.auditStatus === 'rejected') {
          try {
            await ElMessageBox.confirm(
              '检测到此攻略之前被拒绝，修改后将重新提交审核，是否继续？',
              '提示',
              {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }
            )
            
            updatedGuide.status = 'pending'
            updatedGuide.auditStatus = 'pending'
            updatedGuide.isPublished = false
            updatedGuide.originalIsPublished = false
            updatedGuide.auditComment = ''
            updatedGuide.resubmitTime = getCurrentTime()
            
            tableData.value[index] = updatedGuide
            
            addEditHistory(
              updatedGuide, 
              'UPDATE', 
              `修改后重新提交审核，修改了：${changedFields.join('、')}`
            )
            
            ElMessage.success('修改成功，已重新提交审核')
          } catch (e) {
            return
          }
        } else {
          tableData.value[index] = updatedGuide
          
          addEditHistory(
            updatedGuide, 
            'UPDATE', 
            `更新了攻略内容，修改了：${changedFields.join('、')}`
          )
          
          ElMessage.success('修改成功')
        }
      }
    }
    dialogVisible.value = false
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('操作失败，请重试')
  }
}

// 提交审核
const submitAudit = () => {
  if (auditForm.value.result === 'rejected' && !auditForm.value.comment?.trim()) {
    ElMessage.warning('拒绝时必须填写审核意见')
    return
  }

  const index = tableData.value.findIndex(item => item.id === currentAuditGuide.value.id)
  if (index !== -1) {
    const originalGuide = tableData.value[index]
    const isResubmitted = originalGuide.resubmitTime != null
    
    const updatedGuide = {
      ...originalGuide,
      auditStatus: auditForm.value.result,
      status: auditForm.value.result === 'approved' ? 'published' : 'rejected',
      isPublished: false,
      originalIsPublished: false,
      auditComment: auditForm.value.result === 'rejected' ? auditForm.value.comment : '',
      auditTime: getCurrentTime(),
      updateTime: getCurrentTime()
    }
    
    tableData.value[index] = updatedGuide

    addEditHistory(
      updatedGuide,
      auditForm.value.result === 'approved' ? 'AUDIT_APPROVED' : 'AUDIT_REJECTED',
      auditForm.value.result === 'approved' ? 
        `${isResubmitted ? '重新审核通过' : '审核通过'}了该攻略` : 
        `${isResubmitted ? '重新审核拒绝' : '审核拒绝'}：${auditForm.value.comment}`
    )

    ElMessage({
      type: auditForm.value.result === 'approved' ? 'success' : 'warning',
      message: auditForm.value.result === 'approved' ? 
        `${isResubmitted ? '重新审核通过' : '审核通过'}` : 
        `${isResubmitted ? '重新审核拒绝' : '审核拒绝'}：${auditForm.value.comment}`
    })
  }
  auditDialogVisible.value = false
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  // 这里可以重新加载数据
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  // 这里可以重新加载数据
}

// 获取状态类型
const getStatusType = (status) => {
  switch (status) {
    case 'approved':
      return 'success'
    case 'pending':
      return 'warning'
    case 'rejected':
      return 'danger'
    default:
      return 'info'
  }
}

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 'approved':
      return '已发布'
    case 'pending':
      return '待审核'
    case 'rejected':
      return '已拒绝'
    default:
      return '未知'
  }
}

// 显示审核意见
const showAuditComment = (row) => {
  currentAuditComment.value = row.auditComment
  commentDialogVisible.value = true
}
</script>

<style scoped>
.travel-guide-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-area {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.content-box {
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  white-space: pre-line;
  line-height: 1.5;
}

.preview-image {
  width: 100px;
  height: 100px;
  margin-right: 10px;
  margin-bottom: 10px;
  border-radius: 4px;
  cursor: pointer;
}

.audit-status {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 5px;
}

.audit-actions {
  display: flex;
  gap: 5px;
}

.audit-actions .el-button--info {
  background-color: #e6d7f3;
  border-color: #d3b8e6;
  color: #6b4c93;
}

.audit-actions .el-button--info:hover {
  background-color: #d3b8e6;
  border-color: #b38fd9;
  color: #5a3d7a;
}

.el-button--info.history-btn {
  background-color: #ffe4c4;
  border-color: #ffd7a8;
  color: #d2691e;
}

.el-button--info.history-btn:hover {
  background-color: #ffd7a8;
  border-color: #ffc080;
  color: #b35900;
}

.audit-comment-content {
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
  white-space: pre-line;
  line-height: 1.5;
  color: #f56c6c;
}
</style> 